﻿using Microsoft.Live;
using NineDishes.Win8.Data;
using NineDishes.Win8.DataModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace NineDishes.Win8
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class SettingPage : NineDishes.Win8.Common.LayoutAwarePage
    {
        public SettingPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }


        private async void UploadTemplateBtn_Click(object sender, RoutedEventArgs e)
        {
            var res = new Windows.ApplicationModel.Resources.ResourceLoader();

            this.UploadTemplateStatus.Text = res.GetString("UploadStarted");
            this.UploadTemplateBtn.IsEnabled = false;
            try
            {
                var handler = new SkyDriveProcessHandler();
                handler.Progress = new Progress<LiveOperationProgress>((progress) =>
                    {
                        //this.progressBar.Value = progress.ProgressPercentage; 
                        this.UploadTemplateStatus.Text = handler.Content + ":" + progress.ProgressPercentage.ToString("###.0") + "%";
                    });


                SkyDriveLoader loader = new SkyDriveLoader(handler);

                await loader.UploadAll();

                this.UploadTemplateStatus.Text = res.GetString("UploadCompleted");
            }
            catch (Exception ex)
            {
                this.UploadTemplateStatus.Text = res.GetString("UploadFail") + ex.ToString();
            }
            finally
            {
                this.UploadTemplateBtn.IsEnabled = true;
            }
        }


        private async void DownloadBtn_Click(object sender, RoutedEventArgs e)
        {
            var res = new Windows.ApplicationModel.Resources.ResourceLoader();
            this.DownloadStatus.Text = res.GetString("DownloadCompleted");
            this.DownloadBtn.IsEnabled = false;

            try
            {
                var handler = new SkyDriveProcessHandler();
                handler.Progress = new Progress<LiveOperationProgress>((progress) =>
                    {
                        //this.progressBar.Value = progress.ProgressPercentage; 
                        this.DownloadStatus.Text = handler.Content + ":" + progress.ProgressPercentage.ToString("###.0") + "%";
                    });

                SkyDriveLoader loader = new SkyDriveLoader(handler);

                await loader.DownLoadAll();

                this.DownloadStatus.Text = res.GetString("DownloadCompleted");
            }
            catch (Exception ex)
            {
                this.DownloadStatus.Text = res.GetString("DownloadCompleted") + ex.ToString();
            }
            finally
            {
                this.DownloadBtn.IsEnabled = true;
            }
        }
        
        private void ReloadBtn_Click(object sender, RoutedEventArgs e)
        {
            SampleDataSource.Reload();
        }

        private async void LocalClearBtn_Click(object sender, RoutedEventArgs e)
        {
            var res = new Windows.ApplicationModel.Resources.ResourceLoader();

            // Create the message dialog and set its content
            var messageDialog = new MessageDialog(res.GetString("ClearLocalDataComfirm"));

            // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
            messageDialog.Commands.Add(new UICommand(
                res.GetString("Yes"),
                new UICommandInvokedHandler(this.ClearSureCommandInvokedHandler)));
            messageDialog.Commands.Add(new UICommand(
                res.GetString("Cancel")));

            // Set the command that will be invoked by default
            messageDialog.DefaultCommandIndex = 1;

            // Set the command to be invoked when escape is pressed
            messageDialog.CancelCommandIndex = 1;

            // Show the message dialog
            await messageDialog.ShowAsync();


        }

        private async void ClearSureCommandInvokedHandler(IUICommand command)
        {

            this.LocalClearBtn.IsEnabled = false;

            try
            {
                await new SkyDriveLoader(null).ClearLocal();
            }
            finally 
            {
                this.LocalClearBtn.IsEnabled = true;
            }
        }

    }
}
